package com.xsp.mybatisxmlsqlparser.gui;

import cn.hutool.core.util.StrUtil;
import com.xsp.mybatisxmlsqlparser.service.ReadFilesService;
import org.springframework.boot.ApplicationArguments;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ApplicationPanelMain {
    private final ReadFilesService readFilesService;
    private JTextField pathTextField;
    private JTextField outputPathTextField;
    private JLabel fileCountLabel;
    private ScheduledExecutorService scheduler;

    public ApplicationPanelMain(ReadFilesService readFilesService) {
        this.readFilesService = readFilesService;
    }

    public void run(ApplicationArguments args) throws Exception {

        // 创建主框架
        JFrame frame = new JFrame("MybatisXMLSqlParser");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setSize(400, 300);
        // 创建面板并添加组件
        JPanel panel = new JPanel();

        panel.add(new JLabel("文件目录:"));
        pathTextField = new JTextField(20);
        pathTextField.getDocument().addDocumentListener(new DocumentListener() {
            private void scheduleFileCount() {
                if (scheduler != null) {
                    scheduler.shutdownNow();
                }
                scheduler = Executors.newScheduledThreadPool(1);
                scheduler.schedule(() -> countXmlFiles(), 1, TimeUnit.SECONDS); // 1秒后执行计数
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                scheduleFileCount();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                fileCountLabel.setText("0");
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                scheduleFileCount();
            }
        });
        panel.add(pathTextField);

        JButton browseButton = new JButton("浏览...");
        browseButton.addActionListener(e -> browseForDirectory(pathTextField));
        panel.add(browseButton);

        panel.add(new JLabel("输出目录:"));
        outputPathTextField = new JTextField(20);
        panel.add(outputPathTextField);

        JButton browseOutputButton = new JButton("浏览...");
        browseOutputButton.addActionListener(e -> browseForDirectory(outputPathTextField));
        panel.add(browseOutputButton);

        JButton countButton = new JButton("转化");
        countButton.addActionListener(e -> countXmlFiles());
        panel.add(countButton);

        panel.add(new JLabel("已获得的文件数量:"));
        fileCountLabel = new JLabel("0");
        panel.add(fileCountLabel);

        // 创建日志文本区域
        JTextArea logTextArea = new JTextArea();
        logTextArea.setSize(100, 200);
        logTextArea.setEditable(false); // 设置为不可编辑
        logTextArea.setLineWrap(true); // 设置自动换行
        logTextArea.setWrapStyleWord(true); // 设置单词包裹


        // 添加滚动条
        JScrollPane scrollPane = new JScrollPane(logTextArea);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        // 将滚动面板添加到主面板
        panel.add(scrollPane);

        // 将面板添加到框架的内容面板中
        frame.getContentPane().add(panel);
        frame.setVisible(true);

    }

    private void browseForDirectory(JTextField textField) {
        JFileChooser fileChooser = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnValue = fileChooser.showOpenDialog(null);
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
        }
    }

    private void countXmlFiles() {
        String path = pathTextField.getText();
        if (StrUtil.isNotBlank(path)) {
            // 在后台线程中执行文件计数操作，以避免界面冻结
            ExecutorService executor = Executors.newSingleThreadExecutor();
            executor.execute(() -> {
                List<File> xmlFiles = readFilesService.readFiles(path, ".xml");
                SwingUtilities.invokeLater(() -> {
                    fileCountLabel.setText(String.valueOf(xmlFiles.size()));
                });
            });
            executor.shutdown();
        } else {
            JOptionPane.showMessageDialog(null, "请选择一个文件夹", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}
